Java作业展示

复数运算

class Complex {
    private double real;
    private double imag;

    // 构造函数
    public Complex(double real, double imag) {
        this.real = real;
        this.imag = imag;
    }

    // 获取实部
    public double getReal() {
        return real;
    }

    // 获取虚部
    public double getImag() {
        return imag;
    }

    // 加法
    public Complex add(Complex other) {
        double newReal = this.real + other.real;
        double newImag = this.imag + other.imag;
        return new Complex(newReal, newImag);
    }

    // 减法
    public Complex subtract(Complex other) {
        double newReal = this.real - other.real;
        double newImag = this.imag - other.imag;
        return new Complex(newReal, newImag);
    }

    // 乘法
    public Complex multiply(Complex other) {
        double newReal = this.real * other.real - this.imag * other.imag;
        double newImag = this.real * other.imag + this.imag * other.real;
        return new Complex(newReal, newImag);
    }

    // 除法
    public Complex divide(Complex other) {
        double denominator = other.real * other.real + other.imag * other.imag;
        double newReal = (this.real * other.real + this.imag * other.imag) / denominator;
        double newImag = (this.imag * other.real - this.real * other.imag) / denominator;
        return new Complex(newReal, newImag);
    }

    @Override
    public String toString() {
        if (imag == 0) {
            return String.valueOf(real);
        } else if (real == 0) {
            return imag + "i";
        } else if (imag < 0) {
            return real + " - " + (-imag) + "i";
        } else {
            return real + " + " + imag + "i";
        }
    }
}

class Main {
    public static void main(String[] args) {
        Complex c1 = new Complex(1, 2);
        Complex c2 = new Complex(3, 4);

        System.out.println("加法: " + c1.add(c2));
        System.out.println("减法: " + c1.subtract(c2));
        System.out.println("乘法: " + c1.multiply(c2));
        System.out.println("除法: " + c1.divide(c2));
    }
}
            

运行结果

加法: 4.0 + 6.0i
减法: -2.0 - 2.0i
乘法: -5.0 + 10.0i
除法: 0.44 + 0.08i
            

计算1到n的和和n的阶乘

import java.util.Scanner;

public class Homework2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入一个整数n: ");
        int n = scanner.nextInt();

        // 计算1到n的和
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        System.out.println("1到" + n + "的和为: " + sum);

        // 学有余力部分:计算n的阶乘
        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        System.out.println(n + "的阶乘为: " + factorial);

        scanner.close();
    }
}
            

运行结果

请输入一个整数n: 5
1到5的和为: 15
5的阶乘为: 120